//
//  HomePageTopicListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/8.
//  Copyright © 2021 hxh. All rights reserved.
//

#define TabHeadHeight 204
#define MovedHeadHeight 64


typedef enum : NSUInteger {
    XHREFRESHREADY,
    XHREFRESHSTART,
    XHREFRESHIDE,
    XHREFRESHEND,
} XHRefreshType;

#import "HeaderView.h"
#import "HomePageItemModel.h"
#import "MineFollowItemModel.h"
#import "HomePageTopicDetailModel.h"
#import "HomePageDetailViewController.h"
#import "HomePageContentViewController.h"
#import "HomePageUserInfoViewController.h"
#import "HomePageTopicListViewController.h"

@interface HomePageTopicListViewController ()<IGListAdapterDataSource,UIScrollViewDelegate>
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,strong)IGListAdapter *adapter;
@property (nonatomic,strong)IGListCollectionView *collectionView;
@property (nonatomic,strong)UIImageView *headerImgView;
@property (nonatomic,strong)HeaderView *headerView;
@property (nonatomic,strong)NSMutableArray *dataArray;


// 导航栏相关组件
@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UIView *navContainView;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIImageView *backImgView;
@property (nonatomic,strong)UILabel *navLb;
@property (nonatomic,strong)UIImageView *topicFlag;
// 刷新相关组件
@property (nonatomic,strong)UIActivityIndicatorView *spin;
@property (nonatomic,strong)UILabel *loadingLb;
@property (nonatomic,strong)UILabel *loadingDate;

// 发布相关
@property (nonatomic,strong)UIImageView *postImgView;
@property (nonatomic,strong)UILabel *postLb;
@property (nonatomic,strong)UIImageView *postIcon;

@property (nonatomic,assign)XHRefreshType type;
@property (nonatomic,assign)NSInteger page;

@property (nonatomic,strong)HomePageTopicDetailModel *detailModel;

@property (nonatomic,assign)BOOL isLastPage;


@end

@implementation HomePageTopicListViewController


- (UIStatusBarStyle)preferredStatusBarStyle {

    if (self.navView.alpha >= 0.6) {
        return UIStatusBarStyleDefault;
    }
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {

    return UIStatusBarAnimationNone;
}


- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (HeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [[HeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, TabHeadHeight)];
    }
    return _headerView;
}


- (IGListCollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[IGListCollectionView alloc]initWithFrame:CGRectMake(0,MovedHeadHeight, kScreenW, kScreenH-MovedHeadHeight)];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.contentInset = UIEdgeInsetsMake(TabHeadHeight-MovedHeadHeight - 20, 0, 0, 0);
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (IGListAdapter *)adapter {
    if (!_adapter) {
        _adapter = [[IGListAdapter alloc] initWithUpdater:[[IGListAdapterUpdater alloc] init] viewController:self];
    }
    return _adapter;   
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    [MobClick event:@"topic_detail_show"];
    
    self.page = 1;
    
    [self setUI];
    
    [self registNote];
    
    [self showDataLoadState];
    
    [self loadDataSource];
    
}

#pragma mark - 处理通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateItemListStatusSource:) name:@"updateItemListSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteHomePageItem:) name:@"deleteHomePageItem" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateListSource) name:@"updateUserInfoList" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFollowListStatus:) name:@"updateUserInfoFollowListStatus" object:nil];
    
}
- (void)deleteHomePageItem:(NSNotification *)note{
    __block NSInteger index = -1;
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:itemModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];

    if (index != -1) {
        [self.dataArray removeObjectAtIndex:index];
        [self.adapter reloadDataWithCompletion:nil];
    }
    self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
}

- (void)updateFollowListStatus:(NSNotification *)note{
    MineFollowItemModel *itemModel = note.userInfo[@"data"];
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.userId isEqualToNumber:itemModel.userId]) {
            obj.followType = itemModel.followCode;
        }
    }];
    [self.adapter reloadDataWithCompletion:nil];
}

- (void)updateListSource{
    self.page = 1;
    [self showDataLoadState];
    [self loadDataSource];
}

- (void)updateItemListStatusSource:(NSNotification *)note{
    
    [self.adapter reloadDataWithCompletion:nil];
}

#pragma mark - 接口
- (void)loadTopicDetail{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTagById];
    param[@"tagId"] = self.tagModel.tagId;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetTagById) parames:param success:^(id responseObj) {
        
        self.detailModel = [HomePageTopicDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        
        [self.headerView setModel:self.detailModel];
        
    } failure:^(id error) {
            
    }];
}

- (void)loadDataSource{
    
    if (![RPAppManager isLogin]) {
        [self hideDataLoadLoadState];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @(10);
    param[@"tagId"] = self.tagModel.tagId;
    param[@"type"] = @"1";
    param[@"md5"] =  [RPAppManager md5StrWithApi:GetIndexPostList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetIndexPostList) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        if (self.page == 1) {
            [self loadTopicDetail];
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        self.isLastPage = NO;
        
        
        [self.adapter performUpdatesAnimated:NO completion:^(BOOL finished) {
            
            CGFloat bottom = self.collectionView.mj_insetB;
            if (responseObj[RESPONSE][LASTPAGE]) {
                self.isLastPage = YES;
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                if (self.collectionView.mj_footer.cl_height == 44.0f) {
                    if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                        self.collectionView.mj_insetB = 138.0f;
                    }
                    self.collectionView.mj_footer.cl_height = 138.0f;
                }
            }else{
                [self.collectionView.mj_footer resetNoMoreData];
                if (self.collectionView.mj_footer.cl_height == 138.0f) {
                    self.collectionView.mj_footer.cl_height = 44.0f;
                    if (bottom == 138.0f) {
                         self.collectionView.mj_insetB = 44.0f;
                     }
                }
            }
            self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
            
            
            [self resetRefresh];
        }];
        
      
        
        
    } failure:^(NSError *error) {
        
        [self loadTopicDetail];
        
        
        [self hideDataLoadLoadState];
        
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
       
        [self resetRefresh];
    }];
}

- (void)resetRefresh{
    [self.spin stopAnimating];
    self.loadingDate.hidden = YES;
    self.loadingLb.hidden = YES;
    self.loadingLb.text = @"下拉刷新";
    self.type = XHREFRESHREADY;
}

- (void)setUI{
    self.isHideNavBar = YES;
    
    if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0) {
           self.edgesForExtendedLayout = UIRectEdgeNone;
           self.automaticallyAdjustsScrollViewInsets=NO;
    }

    [self.view addSubview:self.headerView];
    
    self.adapter.dataSource = self;
    self.adapter.collectionView = self.collectionView;
    self.adapter.scrollViewDelegate = self;
    
    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadDataSource];
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.collectionView.mj_footer = footer;
    
    self.collectionView.backgroundColor = UIColor.clearColor;
    
    self.view.backgroundColor =  [UIColor whiteColor];
    
    
    self.spin = [[UIActivityIndicatorView alloc] init];
    self.spin.color = [UIColor whiteColor];
    self.spin.hidden = YES;
    [self.view addSubview:self.spin];
    [self.spin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.centerX.equalTo(self.view).offset(-40);
    }];
    
    self.loadingLb = [[UILabel alloc]init];
    self.loadingLb.text = @"下拉刷新";
    self.loadingLb.textColor = UIColor.whiteColor;
    self.loadingLb.font = font(12);
    self.loadingLb.hidden = YES;
    [self.view addSubview:self.loadingLb];
    [self.loadingLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.spin).offset(-5);
        make.left.equalTo(self.spin.mas_right).offset(2);
    }];

    self.loadingDate = [[UILabel alloc]init];
    self.loadingDate.textColor = UIColor.whiteColor;
    self.loadingDate.font = font(8);
    self.loadingDate.hidden = YES;
    [self.view addSubview:self.loadingDate];
    [self.loadingDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loadingLb.mas_bottom);
        make.left.equalTo(self.spin.mas_right).offset(2);
    }];
    
    
    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kNavBarHeight);
    }];
    
    self.navContainView = [[UIView alloc]init];
    [self.navView addSubview:self.navContainView];
    [self.navContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.navView);
        make.height.mas_equalTo(44);
    }];
    
    self.topicFlag = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_topic_nav_selected_tag"]];
    
    self.navLb = [[UILabel alloc]init];
    self.navLb.text = self.tagModel.tagName;
    self.navLb.textColor = RGBA(35, 24, 21, 1);
    self.navLb.font = [UIFont boldSystemFontOfSize:18];
    [self.navContainView addSubview:self.navLb];
    
    
    [self.navContainView addSubview:self.topicFlag];
    
    [self.topicFlag mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navContainView);
        make.right.equalTo(self.navLb.mas_left).offset(-4);
    }];
    

    [self.navLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.navView).offset(15);
        make.centerY.equalTo(self.navContainView);
    }];
    
    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_back_normal_tag"]];
    self.backImgView.highlightedImage = [UIImage imageNamed:@"common_back_tag"];
    [self.view addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navContainView);
        make.left.equalTo(self.view).offset(16);
    }];
    
    
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.navContainView);
        make.width.mas_equalTo(80);
    }];
    
    self.navView.alpha = 0;
    
    
    self.postImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_topic_post_tag"]];
    [self.view addSubview:self.postImgView];
    
    [self.postImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-(GK_SAVEAREA_BTM + 16));
        make.centerX.equalTo(self.view);
    }];
    
    UserInfoModel *userInfo = [UserInfoModel userInfo];
    
    self.postIcon = [[UIImageView alloc]init];
    [self.postIcon sd_setImageWithURL:[NSURL URLWithString:userInfo.imagePath] placeholderImage:[UIImage imageNamed:@"defaut_header"]];
    self.postIcon.layer.cornerRadius = 15;
    self.postIcon.layer.masksToBounds = YES;
    [self.view addSubview:self.postIcon];
    [self.postIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
        make.left.equalTo(self.postImgView).offset(7);
        make.centerY.equalTo(self.postImgView);
    }];
    
    self.postLb = [[UILabel alloc]init];
    self.postLb.text = @"立即发布";
    self.postLb.textColor = [UIColor whiteColor];
    self.postLb.font = [UIFont boldSystemFontOfSize:12];
    [self.view addSubview:self.postLb];
    [self.postLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.postImgView);
        make.left.equalTo(self.postIcon.mas_right).offset(8);
    }];
    
    
    self.postImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(postMethod)];
    [self.postImgView addGestureRecognizer:tap];
    
    [self.adapter reloadDataWithCompletion:nil];
    
}



- (void)postMethod{
    
    
    [SVProgressHUD show];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTagById];
    param[@"tagId"] = self.tagModel.tagId;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetTagById) parames:param success:^(id responseObj) {
   
        HomePageTopicDetailModel *tagModel = [HomePageTopicDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        if (tagModel.disable.intValue == 1) {
            [MGJRouter openURL:@"local://ddup/release" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        }else{
            [MGJRouter openURL:@"local://ddup/release" withUserInfo:@{@"navigationVC":self.navigationController,@"tag":self.tagModel} completion:nil];
        }
    } failure:^(id error) {
            
    }];
    

}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)dateStr{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [formatter stringFromDate:date];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([self.spin isAnimating]) {
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self resetRefresh];
        }else{
            
            [self.collectionView.mj_footer resetNoMoreData];
            
            self.page = 1;
            
            [self loadDataSource];
            
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate) {
        CGFloat y = scrollView.contentOffset.y;
        if (y <= -200) {
            if (self.type == XHREFRESHREADY) {
                self.type = XHREFRESHIDE;
                [self.spin startAnimating];
            }
            self.loadingLb.text = @"正在刷新";
        }else{
            [self resetRefresh];
        }
    }
}
    
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    self.loadingDate.text = [self dateStr];
    
    CGFloat y = scrollView.contentOffset.y;
    if (-y > TabHeadHeight-MovedHeadHeight - 20) {
        _headerView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), (-y)+MovedHeadHeight + 20);
    }else{
        CGFloat alpha = y / (TabHeadHeight-MovedHeadHeight -20);
        if (alpha < 0.0) {
            _headerView.alpha = fabs(alpha);
            _navView.alpha = 1 - fabs(alpha);
        }else{
            _headerView.alpha = 0;
        }
        
        if (self.type == XHREFRESHIDE && fabs(alpha) < 1.0f) {
            self.loadingDate.hidden = YES;
            self.loadingLb.hidden = YES;
            self.spin.hidden = YES;
        }
        
        if (self.type != XHREFRESHIDE) {
            self.loadingDate.hidden = YES;
            self.loadingLb.hidden = YES;
            self.spin.hidden = YES;
        }
    }
    
    if (y <= -200) {
        self.spin.hidden = NO;
        self.loadingDate.hidden = NO;
        self.loadingLb.hidden = NO;
        
        self.navView.alpha = 0;
        
        // 判断如果是非正在请求
        if (self.type != XHREFRESHIDE) {
            // 改成开始请求
            self.type = XHREFRESHREADY;
        }
    }
    
    self.backImgView.highlighted = self.navView.alpha >= 0.6;
    
    
    [self setNeedsStatusBarAppearanceUpdate];
}




#pragma mark - IGListAdapterDataSource
- (NSArray<id <IGListDiffable>> *)objectsForListAdapter:(IGListAdapter *)listAdapter{
    return self.dataArray;
}

- (IGListSectionController *)listAdapter:(IGListAdapter *)listAdapter sectionControllerForObject:(id)object{
   
    IGListSectionController *vc = nil;
    
    if ([object isKindOfClass:[HomePageItemModel class]]){
      
        vc = [[HomePageContentViewController alloc]init];
        HomePageItemModel *lastModel = self.dataArray.lastObject;
        if ([((HomePageItemModel *)object).postId isEqualToNumber:lastModel.postId]) {
            ((HomePageItemModel *)object).hideLine = YES;
        }
   
        ((HomePageItemModel *)object).showRadius = YES;
        ((HomePageContentViewController *)vc).model = object;
        // 查看头像
        __weak typeof(self)weakSelf = self;
        ((HomePageContentViewController *)vc).showUserInfo = ^(NSNumber * _Nonnull userId) {
            
            [MobClick event:@"homePage_show_userInfo"];
            HomePageUserInfoViewController *userInfoVC = [[HomePageUserInfoViewController alloc]initWithUserId:userId];
            [weakSelf.navigationController pushViewController:userInfoVC animated:YES];
        };
        ((HomePageContentViewController *)vc).showDetail = ^(HomePageItemModel * _Nonnull currentModel,BOOL isComment) {
            NSInteger index = [self.dataArray indexOfObject:currentModel];
            XHPageDetailPlatformType platformType = XHPageDetailPlatformTypeNormal;
            if (isComment) {
                // 弹出输入框
                if (currentModel.commentNum.intValue == 0) {
                    platformType = XHPageDetailPlatformTypeBeginText;
                // 弹出评论框
                }else{
                    platformType = XHPageDetailPlatformTypeShowComment;
                }
            }
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[kXHItemType] = @(XHPageDetailItemTypeNormal);
            param[kXHPlatformType] = @(platformType);
            param[kXHShowUserInfo] = @(YES);
            param[kXHListSource] = self.dataArray;
            param[kXHDetailTagId] = self.tagModel.tagId;
            param[kXHCurrentIndex] = @(index);
            param[kXHCurrentPage] = @(self.page);
            HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
            [weakSelf.navigationController pushViewController:dtlVC animated:YES];
        };
        
        ((HomePageContentViewController *)vc).showTopicList = ^(HomeTagItemModel * _Nonnull currentModel) {
            HomePageTopicListViewController *listVC = [[HomePageTopicListViewController alloc]init];
            listVC.tagModel = currentModel;
            [weakSelf.navigationController pushViewController:listVC animated:YES];
        };
        
        vc.inset = UIEdgeInsetsMake(0, 0, 1, 0);
    }
   
    return vc;
}

- (void)updateItemWithCurrentModel:(HomePageItemModel *)itemModel{
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:itemModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        [self.dataArray replaceObjectAtIndex:index withObject:itemModel];
    }
    [self.adapter reloadDataWithCompletion:nil];
}


- (nullable UIView *)emptyViewForListAdapter:(IGListAdapter *)listAdapter{
    UIView *emptyView = [[UIView alloc]initWithFrame:CGRectMake(0,TabHeadHeight-MovedHeadHeight, kScreenW, 300)];
    UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    imgView.center = emptyView.center;
       
    UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    lb.text = @"无内容";
    lb.textColor = RGBA(198, 198, 197, 1);
    lb.font = font(12);
    lb.textAlignment = NSTextAlignmentCenter;
    [emptyView addSubview:lb];
    [emptyView addSubview:imgView];
    lb.cl_y = imgView.cl_bottom + 13;
    
    return emptyView;

}



@end
